package com.jade.core.web.handler;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jade.core.common.constant.ScanPkgConstant;
import com.jade.core.common.entity.BasePage;
import com.jade.core.common.entity.BaseResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 *  全局处理器
 * @author Arnold
 * @version V2.0
 * @date 2021/12/26 10:15
 **/
@RestControllerAdvice(basePackages = {ScanPkgConstant.BASE_PACKAGE})
public class GlobalHandler implements ResponseBodyAdvice<Object> {
    /**
     * 统一相应模板，支持
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;

    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof BaseResult) {
            return o;
        } else if (o instanceof Page) {
            BasePage basePage = new BasePage();
            BeanUtil.copyProperties(o, basePage);
            basePage.setPages(((Page) o).getPages());
            return BaseResult.success(basePage);
        } else {
            return BaseResult.success(o);
        }
    }

}